﻿using Draco.OWF.Metadata;
using Draco.OWF.Metadata.Impl;
using System;
using System.IO;
using System.Xml;

namespace Draco.OWF.Metadata.Serialize
{
    public class XmlSerializer
    {
        public static String SerializeWorkflowProcess(WorkflowModel workflow)
        {
            if (workflow == null) return "";
            using (StringWriter writer = new StringWriter())
            {

                System.Xml.Serialization.XmlSerializer xmlSerializer =
                    new System.Xml.Serialization.XmlSerializer(workflow.GetType());
                xmlSerializer.Serialize(writer, workflow);
                return writer.ToString();
            }
        }

        public static void SerializeWorkflowProcess(WorkflowModel workflow,String filePath)
        {
            if (workflow == null) return;
            using (Stream stream = new FileStream(filePath, FileMode.OpenOrCreate))
            {
                using (StreamWriter writer = new StreamWriter(stream))
                {

                    System.Xml.Serialization.XmlSerializer xmlSerializer =
                        new System.Xml.Serialization.XmlSerializer(workflow.GetType());
                    xmlSerializer.Serialize(writer, workflow);
                }
            }
        }

        public static WorkflowModel DeserializeWorkflowProcess(String content)
        {
            System.Xml.Serialization.XmlSerializer xmlSerializer = 
                new System.Xml.Serialization.XmlSerializer(typeof(WorkflowModelImpl));
            using (var xmlReader = XmlReader.Create(new StringReader(content)))
            {
                var workflowModel = (WorkflowModel)xmlSerializer.Deserialize(xmlReader);
                return workflowModel;
            }
                
        }

        public static WorkflowModel DeserializeWorkflowProcessFromFile(String filepath)
        {
            System.Xml.Serialization.XmlSerializer xmlSerializer =
                new System.Xml.Serialization.XmlSerializer(typeof(WorkflowModelImpl));

            using (Stream iStream = new FileStream(filepath, FileMode.Open))
            {
                var xmlReader = XmlReader.Create(iStream);
                var workflowModel = (WorkflowModel)xmlSerializer.Deserialize(xmlReader);
                return workflowModel;
            }
        }
    }
}
